package com.grj.parking.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.grj.parking.domain.ParkingLot;
import com.grj.parking.service.ParkingLotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;


import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/api/parking-lots")
public class ParkingLotController {

    @Autowired
    private ParkingLotService parkingLotService;

    /**
     * 全量同步数据到ES
     */
    @PostMapping("/sync-to-es")
    public ResponseEntity<String> fullSyncToEs() {
        try {
            boolean success = parkingLotService.fullSyncToEs();
            return success ? ResponseEntity.ok("数据同步成功") :
                    ResponseEntity.internalServerError().body("数据同步失败");
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("同步失败: " + e.getMessage());
        }
    }


    /**
     * 搜索附近的停车场
     */
    @GetMapping("/nearby")
    public ResponseEntity<List<ParkingLot>> searchNearby(
            @RequestParam double latitude,
            @RequestParam double longitude,
            @RequestParam(defaultValue = "1000") double distance,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize) {
        try {
            List<ParkingLot> result = parkingLotService.searchNearby(
                    latitude, longitude, distance, pageNum, pageSize);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 模糊糊查询询停车场名称接口
     * @param lotName 停车场名称关键字糊关键词
     * @param page 页码（从0开始）
     * @param size 每页条数
     * @return 分页查询结果
     */
    @GetMapping("/fuzzy-search")
    public Map<String, Object> fuzzySearchByName(
            @RequestParam(required = false) String lotName,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        // 创建分页对象
        Pageable pageable = PageRequest.of(page, size);

        // 调用服务层执行查询
        Page<ParkingLot> parkingLots = parkingLotService.fuzzySearchByLotName(lotName, pageable);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("total", parkingLots.getTotal());
        result.put("pages", parkingLots.getPages());
        result.put("currentPage", page);
        result.put("size", size);
        result.put("data", parkingLots.getRecords());

        return result;
    }
}
